package org.wtframework.website.server.service;

import java.util.List;

import org.openredhead.springx.core.server.page.IPage;
import org.openredhead.springx.core.web.mvc.ajaxrpc.BasicAjaxRpcRemoteService;
import org.openredhead.springx.core.web.mvc.annotation.AjaxRpcMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wtframework.platform.server.util.WebFileUtil;
import org.wtframework.website.server.manager.WebImageManager;
import org.wtframework.website.server.model.impl.WebImage;

@Service
public class WebImageService extends BasicAjaxRpcRemoteService {
	
	
	@Autowired
	private WebImageManager webimagemanager;
	
	@AjaxRpcMethod
	public String addWebimage(WebImage webimage){
		
		webimage.setImg_url(WebFileUtil.copyFile(webimage.getImg_url(), "webimg_cover"));
		webimagemanager.save(webimage);
		
		return "添加成功";
	}
	@AjaxRpcMethod
	public String updataWebimage(WebImage webimage , String oldUrl){
		
		WebImage webImage = webimagemanager.load(webimage.getId());
		String imgUrl = webimage.getImg_url();
		if(!oldUrl.equals(imgUrl)){
			WebFileUtil.deleteFile(oldUrl);
			imgUrl = WebFileUtil.copyFile(webimage.getImg_url(), "webimg_cover");
			webImage.setImg_url(imgUrl);
		}
		webImage.setLink_url(webimage.getLink_url());
		webImage.setTitle(webimage.getTitle());
		webimagemanager.save(webImage);

		return "修改成功";
	}
	
	@SuppressWarnings("unchecked")
	@AjaxRpcMethod
	public String deletewebimage(List<Integer> idList) {
		String hql = "from WebImage where id in(:idList)";
		
		List<WebImage> webimageList = webimagemanager.getQuery(hql).setParameterList("idList", idList).list();
		
		for(WebImage webImage : webimageList) {
			WebFileUtil.deleteFile(webImage.getImg_url());
			webimagemanager.delete(webImage);
		}
		
		return "删除成功！";
	}
	@AjaxRpcMethod
	public IPage<WebImage> getWebimageListByTitle(Integer pageNo, Integer pageSize, String title){
		
		String hql = "from WebImage where title like ? ";
		
		return webimagemanager.findByQuery(hql, new Object[] {  "%" + title + "%" }).getPageByPageNo(pageNo, pageSize);
	}
	

}
